"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Calendar, User, Tag, BookOpen, PenTool, Users } from "lucide-react";
import { API_ENDPOINTS, apiRequest } from "@/lib/api";
import { mockPosts } from "@/lib/mockData";
import { useQuery } from "@tanstack/react-query";

interface Post {
  id: string;
  title: string;
  slug: string;
  content: string;
  excerpt?: string;
  coverImage?: string;
  published: boolean;
  createdAt: string;
  author: {
    id: string;
    name: string;
  };
  tags: Array<{
    id: string;
    name: string;
  }>;
}

export default function HomePage() {
  const {
    data: posts = [],
    isLoading,
    isError,
    error,
  } = useQuery({
    queryKey: ["posts"],
    queryFn: () => apiRequest<Post[]>(API_ENDPOINTS.POSTS),
    // 失败时自动重试 1 次
    retry: 1,
  });

  // 兼容 mock 数据逻辑
  const [useMockData, setUseMockData] = useState(false);
  const [mocked, setMocked] = useState<Post[]>([]);
  // 仅当请求失败时才用 mock
  useEffect(() => {
    if (isError) {
      setUseMockData(true);
      setMocked(mockPosts.slice(0, 3));
    }
  }, [isError]);

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-2 text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  if (isError && !useMockData) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <p className="text-red-500">
            获取文章列表失败:{" "}
            {error instanceof Error ? error.message : "未知错误"}
          </p>
        </div>
      </div>
    );
  }

  // 渲染 posts 或 mock 数据
  const renderPosts = useMockData ? mocked : posts.slice(0, 3);

  return (
    <div className="min-h-screen">
      {/* Hero Section */}
      <section className="bg-gradient-to-br from-blue-600 to-indigo-700 text-white py-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
          <h1 className="text-4xl md:text-6xl font-bold mb-6">
            欢迎来到我的博客
          </h1>
          <p className="text-xl md:text-2xl mb-8 text-blue-100">
            分享技术、记录生活、传递知识
          </p>
          <div className="flex flex-col sm:flex-row gap-4 justify-center">
            <Link href="/posts">
              <Button size="lg" variant="secondary">
                <BookOpen className="h-5 w-5 mr-2" />
                浏览文章
              </Button>
            </Link>
          </div>
        </div>
      </section>

      {/* Features Section */}
      <section className="py-20 bg-gray-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <h2 className="text-3xl font-bold text-gray-900 mb-4">
              为什么选择我们
            </h2>
            <p className="text-xl text-gray-600">简单、高效、专业的博客平台</p>
          </div>
          <div className="grid md:grid-cols-3 gap-8">
            <Card className="text-center">
              <CardHeader>
                <div className="mx-auto w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center mb-4">
                  <BookOpen className="h-6 w-6 text-blue-600" />
                </div>
                <CardTitle>丰富内容</CardTitle>
                <CardDescription>
                  涵盖技术、生活、思考等多个领域的精彩文章
                </CardDescription>
              </CardHeader>
            </Card>
            <Card className="text-center">
              <CardHeader>
                <div className="mx-auto w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center mb-4">
                  <PenTool className="h-6 w-6 text-green-600" />
                </div>
                <CardTitle>原创写作</CardTitle>
                <CardDescription>
                  所有文章均为原创内容，保证质量和独特性
                </CardDescription>
              </CardHeader>
            </Card>
            <Card className="text-center">
              <CardHeader>
                <div className="mx-auto w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center mb-4">
                  <Users className="h-6 w-6 text-purple-600" />
                </div>
                <CardTitle>社区互动</CardTitle>
                <CardDescription>
                  支持用户注册、评论和互动，构建活跃社区
                </CardDescription>
              </CardHeader>
            </Card>
          </div>
        </div>
      </section>

      {/* Latest Posts Section */}
      <section className="py-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center mb-12">
            <div>
              <h2 className="text-3xl font-bold text-gray-900 mb-2">
                最新文章
              </h2>
              <p className="text-gray-600">发现最新发布的内容</p>
            </div>
            <Link href="/posts">
              <Button variant="outline">查看全部</Button>
            </Link>
          </div>

          {useMockData && (
            <div className="mb-6 p-4 bg-yellow-50 border border-yellow-200 rounded-md">
              <p className="text-sm text-yellow-800">
                📝 当前显示的是演示数据，后端 API 可能未启动
              </p>
            </div>
          )}

          {renderPosts.length === 0 ? (
            <div className="text-center py-12">
              <p className="text-gray-500 text-lg">暂无文章</p>
            </div>
          ) : (
            <div className="grid md:grid-cols-3 gap-8">
              {renderPosts.map((post) => (
                <Card
                  key={post.id}
                  className="hover:shadow-lg transition-shadow"
                >
                  {post.coverImage && (
                    <div className="aspect-video overflow-hidden rounded-t-lg">
                      <img
                        src={post.coverImage}
                        alt={post.title}
                        className="w-full h-full object-cover"
                      />
                    </div>
                  )}
                  <CardHeader>
                    <div className="flex items-center gap-2 mb-2 text-sm text-gray-500">
                      <User className="h-4 w-4" />
                      <span>{post.author.name}</span>
                      <Calendar className="h-4 w-4 ml-2" />
                      <span>{formatDate(post.createdAt)}</span>
                    </div>
                    <CardTitle className="line-clamp-2">
                      <Link
                        href={`/posts/${post.slug}`}
                        className="hover:text-blue-600"
                      >
                        {post.title}
                      </Link>
                    </CardTitle>
                    {post.excerpt && (
                      <CardDescription className="line-clamp-3">
                        {post.excerpt}
                      </CardDescription>
                    )}
                  </CardHeader>
                  <CardContent>
                    {post.tags.length > 0 && (
                      <div className="flex items-center gap-2 mb-4">
                        <Tag className="h-4 w-4 text-gray-400" />
                        <div className="flex flex-wrap gap-1">
                          {post.tags.map((tag) => (
                            <Badge
                              key={tag.id}
                              variant="secondary"
                              className="text-xs"
                            >
                              {tag.name}
                            </Badge>
                          ))}
                        </div>
                      </div>
                    )}
                    <Link href={`/posts/${post.slug}`}>
                      <Button variant="outline" className="w-full">
                        阅读全文
                      </Button>
                    </Link>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </div>
      </section>
    </div>
  );
}
